﻿using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Automator.Tasks.Core;
using Automator.Tasks.Windows;

namespace Automator.Tasks
{
    /// <summary>
    /// Class for make user to choose one of several options
    /// Defined attributes:
    /// Header: Text of condition (like "Select an option")
    /// Options: string that contains all possible options and result values (like option1=value1;optionN=valueN)
    /// </summary>
    public class SwitchTask: Task, ITaskExecutable
    {
        public void Execute(WorkflowExecutionContext context)
        {
            try
            {
                SwitchTaskExecuteWindow window = new SwitchTaskExecuteWindow();
                window.lblHeader.Text = context.DereferenceVariables(this.Attributes["Header"].Value);
                
                string[] strings = context.DereferenceVariables(this.Attributes["Options"].Value).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strings)
                {
                    string[] keyValue = s.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (keyValue.Length > 1)
                    {
                        window.pnlContent.Children.Add(
                            new RadioButton()
                            {
                                Margin = new Thickness(32,4,32,4),
                                Content = keyValue[0],
                                Tag = keyValue[1]
                            }
                           );
                    }
                }
                
                context.Argument = null;
                window.footer.BtnOK.Click += delegate { window.DialogResult = true; };                
                if (window.ShowDialog() == true)
                {
                    foreach (UIElement element in window.pnlContent.Children)
                        if (element is RadioButton && (element as RadioButton).IsChecked.Value)
                        {
                            context.Argument = (element as RadioButton).Tag;
                            break;
                        }
                }
                else
                    throw new Exception("User didn't make a choice");
            }
            catch (Exception ex)
            {
                throw new TaskExecutionException(ex.Message, ex);
            }
        }
        
        public SwitchTask():
            base()
        {
            this.Title = "Switch";
            this.Description = "Select an option";
            this.TaskImage = new BitmapImage(new Uri("/Automator.Tasks;component/Resources/switch.png", UriKind.Relative));

            this.Attributes.Add(new TaskAttributeDefinition() { Key = "Header", Value = "Select an option" });
            this.Attributes.Add(new TaskAttributeDefinition() { Key = "Options", Value = String.Empty });
        }
        
        public override string CommandText
        {
            get { return Attributes["Header"].Value.ToString().Trim(); }
            set { base.CommandText = value; }
        }
        
        public override bool EditTask()
        {            
            base.EditTask();
            SwitchTaskEditWindow window = new SwitchTaskEditWindow();
            window.Owner = Application.Current.MainWindow;
            window.Title = String.Format("Edit {0} Task", this.Title);
            //performing binding to the header
            window.header.ContentPanel.DataContext = this;

            ObservableCollection<SwitchTaskOption> options = new ObservableCollection<SwitchTaskOption>();
            options.Add(new SwitchTaskOption() { Text = "Choose 1", Result = 1 });
            string[] strings = this.Attributes["Options"].Value.ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (strings.Length > 0) options.Clear();
            foreach (string s in strings)
            {
                string[] keyValue = s.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                if (keyValue.Length > 0)
                {
                    SwitchTaskOption option = new SwitchTaskOption();
                    option.Text = keyValue[0];
                    if (keyValue.Length > 1)
                        option.Result = keyValue[1];
                    options.Add(option);
                }
            }
            
            window.edtHeader.Text = this.Attributes["Header"].Value.ToString();
            window.gridOptions.ItemsSource = options;            
            window.footer.BtnOK.Click += delegate { window.DialogResult = true; };

            if (window.ShowDialog() == true)
            {
                this.Attributes["Header"].Value = window.edtHeader.Text.Trim();
                
                StringBuilder sb = new StringBuilder();
                foreach (SwitchTaskOption option in options)                  
                    sb.Append(String.Format("{0}={1};", option.Text, option.Result));
                this.Attributes["Options"].Value = sb.ToString();
                
                this.CommandText = String.Empty;
                return true;
            }
            else return false;
        }
    }
    
    public class SwitchTaskOption
    {
        public string Text { get; set; }
        public object Result { get; set; }
    }
}
